package com.wchen.project.zk.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

/**
 * @Desc:   使用 Curator 接口来获取节点数据内容
 * @author: cww
 * @DateTime: 2020-01-23 22:44
 */

public class ZkGetDataByCurator {
    static String path = "/zk-book/c1";
    static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("home:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000,3))
            .build();

    public static void main(String[] args) throws Exception {
        client.start();
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path, "init".getBytes());
        Stat stat = new Stat();
        System.out.println(new String(client.getData().storingStatIn(stat).forPath(path)));
    }

    /**
     * curator 读取数据的 API
     */
    public void getDataMethod() throws Exception{
        // 取一个节点数据内容
        client.getData().forPath(path);
        // 去读一个节点的数据内容，同时获取到该节点的 stat
        Stat stat = new Stat();
        client.getData().storingStatIn(stat).forPath(path);
    }
}
